﻿using System;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.Video;
using Random = System.Random;

public class TMPWave : MonoBehaviour
{
    private bool isPlaying = false;
    private TMP_Text tmpText;
    private Mesh mesh;
    private Vector3[] myVecs;
    private Vector3[] originVecs;
    private Vector3[] offsets;

    public float interval = 0.08f;
    public float waveLength = 0.5f;
    public float waveFrequency = 5;
    public float randomOffset = 0.5f;
    private float startTime;

    private void OnDisable()
    {
        isPlaying = false;
    }

    public void Play()
    {
        isPlaying = true;
        tmpText = GetComponentInChildren<TMP_Text>();
        tmpText.ForceMeshUpdate();
        originVecs = tmpText.mesh.vertices;
        offsets = new Vector3[originVecs.Length];
        for (int i = 0; i < offsets.Length; i+= 4)
        {
            float random = (i / 4) % 2 == 1 ? randomOffset : 0;//UnityEngine.Random.Range(-randomOffset, randomOffset);
            float x = random / 3;
            offsets[i] = new Vector3(x, random);
            offsets[i + 1] += new Vector3(x, random);
            offsets[i + 2] += new Vector3(x, random);
            offsets[i + 3] += new Vector3(x, random);
        }
        startTime = Time.time;
    }
    
    void LateUpdate()
    {
        if (!isPlaying)
        {
            return;
        }
        tmpText.ForceMeshUpdate();
        mesh = tmpText.mesh;
        myVecs = mesh.vertices;
        float currentTime = Time.time - startTime;
        for (int i = 0; i < tmpText.textInfo.characterCount; i++)
        {
            TMP_CharacterInfo c = tmpText.textInfo.characterInfo[i];

            int index = c.vertexIndex;

            float charactorTime = currentTime - i * interval;
            float duration = 1 / waveFrequency;
            Vector3 offset = Vector3.zero;
            if (charactorTime >= 0 && charactorTime <= duration)
            {
                offset = Wobble(charactorTime);
            }
            myVecs[index] = originVecs[index] + offset + offsets[index];
            myVecs[index + 1] = originVecs[index + 1] + offset + offsets[index + 1];
            myVecs[index + 2] = originVecs[index + 2] + offset + offsets[index + 2];
            myVecs[index + 3] = originVecs[index + 3] + offset + offsets[index + 3];
        }

        mesh.vertices = myVecs;
        tmpText.canvasRenderer.SetMesh(mesh);
        
    }
    Vector2 Wobble(float time) {
        return new Vector2(0, Mathf.Sin(time * waveFrequency * Mathf.PI) * waveLength);
    }
}
